package com.ckh.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckh.springboot.common.Result;
import com.ckh.springboot.dto.ExamCreateDTO;
import com.ckh.springboot.entity.ExamSchedule;
import com.ckh.springboot.service.IExamScheduleService;
import com.ckh.springboot.dto.StudentExamSubmitDTO;
import com.ckh.springboot.entity.Exam;
import com.ckh.springboot.entity.ExamQuestion;
import com.ckh.springboot.entity.QuestionBank;
import com.ckh.springboot.entity.StudentExamAnswer;
import com.ckh.springboot.service.IExamQuestionService;
import com.ckh.springboot.service.IExamService;
import com.ckh.springboot.service.IQuestionBankService;
import com.ckh.springboot.service.IStudentExamAnswerService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.ckh.springboot.service.ISysClassService;
import com.ckh.springboot.entity.SysClass;
import com.ckh.springboot.entity.JoinClass;
import com.ckh.springboot.service.IJoinClassService;
import com.ckh.springboot.entity.User;
import com.ckh.springboot.service.IUserService;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/exam")
public class ExamController {

    @Resource
    private IExamService examService;
    @Resource
    private IExamQuestionService examQuestionService;
    @Resource
    private IQuestionBankService questionBankService;
    @Resource
    private IStudentExamAnswerService studentExamAnswerService;
    @Resource
    private IExamScheduleService examScheduleService; // 新增
    @Resource
    private ISysClassService sysClassService; // 注入班级服务
    @Resource
    private IJoinClassService joinClassService; // 新增：注入 joinClassService
    @Resource
    private IUserService userService; // 注入用户服务

    // 创建考试
    @PostMapping("/create")
    public Result create(@RequestBody ExamCreateDTO dto) {
        Exam exam = new Exam();
        exam.setTitle(dto.getTitle());
        exam.setExamTime(dto.getExamTime());
        exam.setTeacherId(dto.getTeacherId());
        exam.setLocation(dto.getLocation()); // 新增
        exam.setTeacher(dto.getTeacher());   // 新增
        exam.setClassId(dto.getClassId()); // 新增：设置班级ID
        examService.save(exam);

        for (Integer qid : dto.getQuestionIds()) {
            ExamQuestion eq = new ExamQuestion();
            eq.setExamId(exam.getId());
            eq.setQuestionId(qid);
            examQuestionService.save(eq);
        }
         // 新增：同步插入考试安排表
         ExamSchedule schedule = new ExamSchedule();
         schedule.setTitle(dto.getTitle());
         schedule.setExamTime(dto.getExamTime());
         schedule.setLocation(dto.getLocation());
         schedule.setTeacher(dto.getTeacher());
         schedule.setCreateTime(new Date());
         schedule.setStatus(1); // 可根据实际业务设定状态
         examScheduleService.save(schedule);
 
        return Result.success();
    }

     // 获取考试列表（可根据身份和班级筛选）
     @GetMapping("/listByUser")
     public Result listByUser(@RequestParam Integer userId, @RequestParam Integer identity, @RequestParam(required = false) Integer classId) {
         List<Exam> exams;
         if (identity == 1) { // 老师
             exams = examService.list(new QueryWrapper<Exam>().eq("teacher_id", userId));
         } else { // 学生
             // 查询学生所有班级ID
            List<JoinClass> joinClasses = joinClassService.list(new QueryWrapper<JoinClass>().eq("user_id", userId));
            List<Integer> classIds = joinClasses.stream().map(JoinClass::getClassId).collect(Collectors.toList());
            if (!classIds.isEmpty()) {
                exams = examService.list(new QueryWrapper<Exam>().in("class_id", classIds));
            } else {
                exams = new ArrayList<>(); // 没有班级则不显示考试
            }
          // for (Exam exam : exams) {
          //   // 查询班级名称
          //   if (exam.getClassId() != null) {
          //     SysClass sysClass = sysClassService.getById(exam.getClassId());
          //     if (sysClass != null) {
          //         exam.setClassName(sysClass.getName());
          //     }
          //   }
          //   long count = studentExamAnswerService.count(
          //       new QueryWrapper<StudentExamAnswer>()
          //           .eq("exam_id", exam.getId())
          //           .eq("student_id", userId)
          //   );
          //   exam.setHasSubmitted(count > 0);
          // }
         }
          // ★★★ 统一为所有考试查班级名称 ★★★
          for (Exam exam : exams) {
            if (exam.getClassId() != null) {
                SysClass sysClass = sysClassService.getById(exam.getClassId());
                if (sysClass != null) {
                    exam.setClassName(sysClass.getName());
                }
            }
            // 学生端处理提交状态
            if (identity == 0) {
                long count = studentExamAnswerService.count(
                    new QueryWrapper<StudentExamAnswer>()
                        .eq("exam_id", exam.getId())
                        .eq("student_id", userId)
                );
                exam.setHasSubmitted(count > 0);
            }
        }
        return Result.success(exams);
     }

   // 获取考试详情（含题目）
    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Exam exam = examService.getById(id);
        // 新增：查班级名称
        if (exam != null && exam.getClassId() != null) {
          SysClass sysClass = sysClassService.getById(exam.getClassId());
          if (sysClass != null) {
              exam.setClassName(sysClass.getName());
          }
        }
        List<ExamQuestion> eqs = examQuestionService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ExamQuestion>().eq("exam_id", id));
        List<QuestionBank> questions = questionBankService.listByIds(
            eqs.stream().map(ExamQuestion::getQuestionId).collect(Collectors.toList()));
        Map<String, Object> data = new HashMap<>();
        data.put("exam", exam);
        data.put("questions", questions);
        return Result.success(data);
    }

   // 学生提交答卷
   @PostMapping("/submit")
   public Result submit(@RequestBody StudentExamSubmitDTO dto) {
       for (StudentExamSubmitDTO.AnswerItem item : dto.getAnswers()) {
           StudentExamAnswer answer = new StudentExamAnswer();
           answer.setExamId(dto.getExamId());
           answer.setStudentId(dto.getStudentId());
           answer.setQuestionId(item.getQuestionId());
           answer.setAnswer(item.getAnswer());
           answer.setSubmitTime(new Date());
           studentExamAnswerService.save(answer);
       }
       return Result.success();
   }

     // 老师查看考试提交情况（返回提交人数和明细）
     @GetMapping("/submitStatus")
     public Result submitStatus(@RequestParam Integer examId) {
        List<StudentExamAnswer> answers = studentExamAnswerService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<StudentExamAnswer>().eq("exam_id", examId));
        // 统计提交人数
        Set<Integer> studentIds = new HashSet<>();
        for (StudentExamAnswer a : answers) {
            studentIds.add(a.getStudentId());
        }
         // ★★★ 查询学生姓名并补充到每个 answer ★★★
        Map<Integer, String> studentIdNameMap = new HashMap<>();
        if (!studentIds.isEmpty()) {
            List<User> users = userService.list(new QueryWrapper<User>().in("id", studentIds));
            for (User u : users) {
                studentIdNameMap.put(u.getId(), u.getName());
            }
        }
        // 查询本场考试所有题目的标准答案和分数
        List<ExamQuestion> eqs = examQuestionService.list(
          new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ExamQuestion>().eq("exam_id", examId));
        Map<Integer, QuestionBank> questionMap = new HashMap<>();
        if (!eqs.isEmpty()) {
            List<Integer> qids = eqs.stream().map(ExamQuestion::getQuestionId).collect(Collectors.toList());
            List<QuestionBank> qbs = questionBankService.listByIds(qids);
            for (QuestionBank qb : qbs) {
                questionMap.put(qb.getId(), qb);
            }
        }
        // 计算每个学生的得分
        Map<Integer, Integer> studentScoreMap = new HashMap<>();
        for (Integer sid : studentIds) {
            int score = 0;
            for (StudentExamAnswer a : answers) {
                if (a.getStudentId().equals(sid)) {
                    QuestionBank qb = questionMap.get(a.getQuestionId());
                    if (qb != null && qb.getAnswer() != null) {
                        // 只判选择题/判断题，填空题可根据需要扩展
                        String stdAnswer = qb.getAnswer().trim();
                        String stuAnswer = a.getAnswer() == null ? "" : a.getAnswer().trim();
                        if (stdAnswer.equals(stuAnswer)) {
                            score += qb.getScore() == null ? 0 : qb.getScore();
                        }
                    }
                }
            }
            studentScoreMap.put(sid, score);
        }
        // 返回答题详情及分数
        List<Map<String, Object>> answerList = new ArrayList<>();
        for (StudentExamAnswer a : answers) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", a.getId());
            map.put("examId", a.getExamId());
            map.put("studentId", a.getStudentId());
            map.put("questionId", a.getQuestionId());
            map.put("answer", a.getAnswer());
            map.put("submitTime", a.getSubmitTime());
            map.put("studentName", studentIdNameMap.getOrDefault(a.getStudentId(), "学生" + a.getStudentId()));
            map.put("score", studentScoreMap.getOrDefault(a.getStudentId(), 0)); // 新增：分数
            answerList.add(map);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("submitCount", studentIds.size());
        data.put("answers", answerList);
        data.put("studentScoreMap", studentScoreMap); // 新增：所有学生分数
        return Result.success(data);
     }
}